import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:reabampos/src/reabam/operation/db/objectbox.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui/support/support_control_devices.dart';
import 'package:reabampos/src/reabam/ui/support/support_upload_order_paylist.dart';
import 'package:reabampos/src/reabam/ui_self_service/member/pagestate_ss_select_member.dart';
import 'package:reabampos/src/reabam/ui_self_service/pagestate_ss_login.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_shoppingcart.dart';
import 'package:reabampos/src/reabam/utils/brean/c_bean_good_item.dart';
import 'package:reabampos/src/reabam/utils/rb_aliyun_log.dart';
import 'package:reabampos/src/reabam/utils/rb_business.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/plugin/x_utils_flutter_plugin.dart';

import 'mine/pagestate_ss_setting_login.dart';

/*
自助收银首页
 */
class StatePageSelfServiceHomeIndex extends XPageState {
  late XFunctionNotifyStateChangeListener _notifyGlobalHandlerListener;

  @override
  void onCreate() {
    super.onCreate();
    RBConfigs.isPageScanType = 0;

    //初始化android设备(商米机等)
    _initAndroid();

    //
    _getWifiIP();

    //文字转语音
    XTTSUtils.initTts(rate: XFlutterUtils.isiOS() ? 0.5 : 1);
    //获取服务端时间
    _checkServerTime();

    //更新设备记录设置
    SupportControlDevices.init(this);

    //登录成功初始化
    _loginSuccessInit();

    _notifyGlobalHandlerListener = (String key, dynamic value) {
      XLogUtils.printLog('---_notifyGlobalHandlerListener,key=$key');
      if (key == 'backToLoginPage') {
        //
        startPage(StatePageSelfServiceLogin(), cleanUntilRetainPageName: '/');
      } else if (key == 'changeCompany') {
        XLogUtils.printLog('---切换门店');
        //登录成功初始化
        _loginSuccessInit();
      } else if (key == 'succeedPayPrintOrder') {
        XLogUtils.printLog('---打印小票');
        _succeedPayPrintOrder(value);
      }
    };

    XNotifyStateChangeUtils.receiveChangeNotify(
      action: RBConfigs.Notify_Global_Handler,
      listener: _notifyGlobalHandlerListener,
    );
  }

  @override
  void onResumed() {
    super.onResumed();
    RBConfigs.isPageScanType = 0;
  }

  void _loginSuccessInit() {
    //初始化阿里云日志
    RBBaseApi.initAliyunLog('自助收银');

    String companyId = XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    XLogUtils.printLog('---开始数据库初始化,companyId=$companyId');
    //objectbox database
    XObjectBoxUtils.create(
        this, XStringUtils.isEmpty(companyId) ? 'default_db' : companyId);

    //获得设备号
    _initMachineCode();

    _initSomeData();

    //初始化socket设备
    XSocketUtils.init();
    //初始化远程设备(快麦云设备)
    XRemoteDeviceUtils.init();
    //初始化蓝牙设备
    XBluetoothBLEUtils.init();
    //初始化usb设备
    XUsbUtils.init();
    //初始化usbSerial设备
    XUsbSerialUtils.init();

    //重新获取支付方式和商品分类
    //RBBaseApi.initGetPayTypeAndGoodType();

    //更新设备记录设置
    SupportControlDevices.initAllDevicesNoteSetting();

    //登录成功重新检测和处理未上传订单2.0
    SupportUploadOrderAndPay.loginInitCheckUnUploadOrderTaskX();
  }

  @override
  void onDestroy() {
    super.onDestroy();
    XNotifyStateChangeUtils.unReceiveChangeNotify(
        action: RBConfigs.Notify_Global_Handler,
        listener: _notifyGlobalHandlerListener);
  }

  //打印小票
  void _succeedPayPrintOrder(dynamic orderId) {
    Map<String, dynamic> printDataJson = {};
    printDataJson['外卖订单参数'] = [];
    printDataJson['标签表'] = [];
    printDataJson['会员表'] = [];
    printDataJson['点餐表'] = [];
    printDataJson['配送表'] = [];

    //门店
    Map<String, dynamic> companyMap = {};
    companyMap['门店别名'] =
        XSharePreferencesUtils.getString(RBConfigs.SP_CompanyName);
    printDataJson['门店表'] = [companyMap];

    //订单
    Map<String, dynamic> orderMap = {};
    orderMap['单据编号'] = orderId;
    orderMap['商户'] = XSharePreferencesUtils.getString(RBConfigs.SP_CompanyName);
    orderMap['单据类型'] = '零售';
    orderMap['收银状态'] = '已收银';
    orderMap['创建时间'] = XDateUtils.getCurrentTime_String();
    orderMap['总数'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity'] ?? 0,
        n: 0);
    orderMap['实收金额'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    orderMap['商品总额'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    orderMap['打印时间'] = XDateUtils.getCurrentTime_String();
    orderMap['配送方式'] = '到店自提';
    //
    printDataJson['订单主表'] = [orderMap];

    //商品
    printDataJson['订单行表'] = [];
    for (ComponentBeanGoodItem iitem
        in RBBusinessUtils.list_shoppingcart_selfService) {
      Map<String, dynamic> itemsMap = {};
      itemsMap['orderItemId'] = iitem.id;
      itemsMap['SKU码'] = iitem.skuBarcode;
      itemsMap['商品名称'] = iitem.itemName;
      itemsMap['规格名称'] = iitem.specName;
      itemsMap['数量'] = iitem.currentQuantity;
      itemsMap['单位'] = iitem.unit;
      itemsMap['总数'] = '${itemsMap['数量']}${itemsMap['单位']}';
      itemsMap['行小计'] = iitem.currentMoney;
      //
      printDataJson['订单行表'].add(itemsMap);
    }

    //支付
    Map<String, dynamic> payMap = {};
    payMap['方式'] = RBConfigs.payParentTypeName;
    payMap['金额'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    payMap['时间'] = XDateUtils.getStringTimeFormat();
    payMap['商家实收金额'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    payMap['金额(含优惠)'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    payMap['客付款'] = XNumberUtils.formatDoubleX(
        RBBusinessUtils.shoppingcartInfo_selfService['totalMoney'] ?? 0,
        n: 2);
    printDataJson['支付表'] = [payMap];

    //
    Map<String, dynamic> data = {};
    data['orderId'] = orderId;
    data['orderNo'] = orderId;
    data['printerTag'] = '2';
    data['printIndex'] = 1;
    data['kmId'] =
        XSharePreferencesUtils.getString(RBConfigs.SP_kuaimai_templateId);
    data['kmCmdType'] = 'getTicketData';
    data['printDataJson'] = XJsonUtils.obj2Json(printDataJson);
    data['kmItemsId'] = 10;
    data['kmUserId'] = '15021708859';
    data['kmPrintH5Id'] = '${XDateUtils.getCurrentTime_ms()}';

    Future(() {
      SupportControlDevices.needPrint(this, data);
    });
  }

  void _initMachineCode() {
    int machineCode = XSharePreferencesUtils.getInt(RBConfigs.SP_MachineCode);
    if (machineCode == 0) {
      RBBaseApi.getMachineCode(succeed: (response,
          Map<String, dynamic> responseMap,
          Map<String, dynamic> headers_response) {
        int machineCode1 = XNumberUtils.dynamic2int(responseMap['data']);
        XLogUtils.printLog('---machineCode=$machineCode1');
        XSharePreferencesUtils.saveInt(RBConfigs.SP_MachineCode, machineCode1);
      }, failed: (String code, String msg) {
        Future.delayed(const Duration(seconds: 3), () {
          _initMachineCode();
        });
      });
    }
  }

  //初始化android设备(商米机等)
  void _initAndroid() async {
    if (XFlutterUtils.isAndroid()) {
      reSetReceiveNativeMessageCallback_XSDKFlutterPlugin();

      //
      Map<String, dynamic> deviceInfo = await XFlutterUtils.getDeviceInfo();
      XLogUtils.printLog('---Android deviceInfo= $deviceInfo');
      dynamic brand = deviceInfo['brand'];
      dynamic model = deviceInfo['model'];
      dynamic version = deviceInfo['version'];

      //初始化支付宝碰一碰设备sdk,参数固定
      Map<String, Object> map_alipayiot = {};
      map_alipayiot['appId'] = '2021004177679101';
      map_alipayiot['pId'] = '2088611935241475';

      //
      if (XStringUtils.equalsIgnoreCase('SUNMI', brand)) {
        //初始化商米机
        XLogUtils.printLog('---初始化商米机');
        RBConfigs.isShangMiDevice = true;
        XFlutterPluginUtils.initShangMiSDK();

        //是否使用商米打印
        RBConfigs.isUserShangMiPrint = XSharePreferencesUtils.getBool(
            RBConfigs.SP_isUseShangMiPrinter,
            defaultValue: true);
        RBConfigs.isUserShangMiSerialWeigher = XSharePreferencesUtils.getBool(
            RBConfigs.SP_isUseShangMiSerialWeigher,
            defaultValue: true);

        if ('$model'.startsWith('T1') || '$model' == 'T2') {
          //初始化支付宝碰一碰设备sdk,实测D2_d_2nd android 11 崩溃
          XFlutterPluginUtils.initAlipayIotSDK(
              XJsonUtils.obj2Json(map_alipayiot));
        } else {
          //实测商米D2_xx android 11初始化正常, 开放其他商米设备初始化,如闪退则smile不兼容导致
          XFlutterPluginUtils.initAlipayIotSDK(
              XJsonUtils.obj2Json(map_alipayiot));
        }
      } else if (XStringUtils.equalsIgnoreCase('HUAWEI', brand)) {
        //华为平板 初始化支付宝碰一碰设备sdk,实测有些设备闪退,smile不兼容导致
        /*
        cd D:\Android\Sdk\platform-tools
        ./adb devices
        ./adb shell logcat >smile.log
        ./adb -s 192.168.8.98:5555 shell logcat >smile.log
         */

        // if(version=='12'){
        //   //实测华为 android 12 初始化正常
        //   XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        // }
        //实测华为 android 12 初始化正常, 开放其他华为平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(
            XJsonUtils.obj2Json(map_alipayiot));
      } else {
        //开放其他品牌平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(
            XJsonUtils.obj2Json(map_alipayiot));
      }
    }
  }

  void reSetReceiveNativeMessageCallback_XSDKFlutterPlugin() {
    if (XFlutterUtils.isAndroid()) {
      XFlutterPluginUtils.setReceiveNativeMessageCallback((resultMap) {
        //{"type":"XSecondScreen","data":"{\"type\":\"getOfflineShopCart\"}"}
        String type = resultMap['type'] ?? '';
        if (type == 'XSecondScreen') {
          Map<String, dynamic> data = XJsonUtils.json2Map(resultMap['data']);
          String t1 = data['type'] ?? '';
          if (t1 == 'getOfflineShopCart') {
            //第二屏幕需要获得购物车
            //supportGetGoodItems.getOfflineShopCart(isSecondScreen:true);
          } else if (t1 == 'getH5SaveValue') {
            //
            String key = data['data'] ?? '';
            //_handle_getH5SaveValue(key,isSecondScreen:true);
          }
        } else if (type == 'AlipayIot_init') {
          //支付宝碰一碰硬件初始化
          String dataJson = resultMap['data'] ?? '';
          //阿里云日志
          XAliyunLogUtils.sendLog(
              RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(),
              '---AlipayIot初始化返回:$dataJson');
        } else if (type == 'AlipayIot_commonPay') {
          //支付宝碰一碰硬件 普通支付
          String dataJson = resultMap['data'] ?? '';
          //runJSFunction(jsFunction_getAppValue('BPaaSCashier',dataJson));

          XLogUtils.printLog('---AlipayIot_commonPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(
              RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(),
              '---AlipayIot_commonPay返回:$dataJson');
        } else if (type == 'AlipayIot_memberPay') {
          //支付宝碰一碰硬件 会员支付
          String dataJson = resultMap['data'] ?? '';
          //runJSFunction(jsFunction_getAppValue('BPaaSNfcMemberPay',dataJson));

          XLogUtils.printLog('---AlipayIot_memberPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(
              RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(),
              '---AlipayIot_memberPay返回:$dataJson');
        } else if (type == 'AlipayIot_memberCard') {
          //支付宝碰一碰硬件 会员开卡登录
          String dataJson = resultMap['data'] ?? '';
          //runJSFunction(jsFunction_getAppValue('BPaaSNfcMember',dataJson));

          XLogUtils.printLog('---AlipayIot_memberCard=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(
              RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(),
              '---AlipayIot_memberCard返回:$dataJson');
        }
      });
    }
  }

  void _getWifiIP() async {
    RBConfigs.localIP = await XWifiUtils.getWifiIP();
    XLogUtils.printLog('---localIP=${RBConfigs.localIP}');
  }

  void _checkServerTime() {
    RBBaseApi.getServerTime(succeed: (response,
        Map<String, dynamic> responseMap,
        Map<String, dynamic> headersResponse) {
      double longt = XNumberUtils.dynamic2double(responseMap['data']) ?? 0.0;
      if (longt > 0) {
        double dif = (longt - XDateUtils.getCurrentTime_ms()).abs();
        //XLogUtils.printLog('---difTime=$dif');
        if (dif > 10 * 60 * 1000) {
          XFlutterUtils.openAlertDialogDefault(
              context: context,
              title: '设备时间',
              contentStr: '当前设备时间有误,请校准后再使用?',
              isShowCancelButton: false,
              onCallbackResult: (String? bt) {
                if ('确定' == bt) {
                  XFlutterUtils.closeApp();
                }
              });
        }
      }
    }, failed: (String code, String msg) {
      //
    });
  }

  @override
  bool getCanHardwarePressBack() {
    return false;
  }

  @override
  Widget getBodyWidget(BuildContext context) {
    return XWidgetUtils.getLayoutContainer(
        child: XWidgetUtils.getLayoutColumn(children: [
      XWidgetUtils.getLayoutContainer(
          margin: XWidgetUtils.getEdgeInsets(50, 46, 0, 0),
          child: XWidgetUtils.getLayoutRow(children: [
            XImageUtils.getImageWidgetWithAsset(
              'reabam_logo_5.png',
              width: 200,
              height: 52,
            ),
            const Spacer(),
            XWidgetUtils.getWidgetGestureDetector(
                child: XWidgetUtils.getLayoutContainer(
                    backgroundColor: Colors.white,
                    child: XWidgetUtils.getLayoutRow(children: [
                      XImageUtils.getImageWidgetWithAsset(
                        'setting1.png',
                        width: 46,
                        height: 46,
                      ),
                      XWidgetUtils.getWidgetText('设置',
                          style: XStyleUtils.getTextStyle(
                            fontSize: 38,
                            color: RBColors.reabamColor4,
                          ),
                          padding: XWidgetUtils.getEdgeInsets(7, 0, 50, 0))
                    ])),
                onTap: () {
                  startPage(PageStateSelfServiceSettingLogin());
                })
          ])),
      XWidgetUtils.getLayoutContainer(
          margin: XWidgetUtils.getEdgeInsets(0, 183, 0, 0),
          alignment: Alignment.center,
          child: XWidgetUtils.getWidgetText(
            '欢迎使用自助收银',
            textAlign: TextAlign.center,
            style: XStyleUtils.getTextStyle(
              fontSize: 80,
              color: RBColors.reabamColor4,
            ),
          )),
      XWidgetUtils.getLayoutContainer(
          margin: XWidgetUtils.getEdgeInsets(125, 91, 125, 0),
          child: XWidgetUtils.getLayoutRow(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                XWidgetUtils.getLayoutContainer(
                    child: XWidgetUtils.getLayoutColumn(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        shrinkWrap: true,
                        children: [
                      XImageUtils.getImageWidgetWithAsset(
                        'ss_homeindex_1.png',
                        width: 120,
                        height: 120,
                      ),
                      XWidgetUtils.getWidgetText(
                        '选择会员\n或非会员购物',
                        textAlign: TextAlign.center,
                        style: XStyleUtils.getTextStyle(
                          fontSize: 26,
                          color: RBColors.reabamColor4,
                        ),
                      ),
                    ])),
                XWidgetUtils.getLayoutExpanded(XWidgetUtils.getLayoutContainer(
                  alignment: Alignment.topCenter,
                  margin: XWidgetUtils.getEdgeInsets(0, 45, 0, 0),
                  child: XImageUtils.getImageWidgetWithAsset(
                    'ss_arr_right.png',
                    width: 40,
                    height: 40,
                  ),
                )),
                XWidgetUtils.getLayoutExpanded(
                  XWidgetUtils.getLayoutContainer(
                      child: XWidgetUtils.getLayoutColumn(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          shrinkWrap: true,
                          children: [
                        XImageUtils.getImageWidgetWithAsset(
                          'ss_homeindex_2.png',
                          width: 120,
                          height: 120,
                        ),
                        XWidgetUtils.getWidgetText(
                          '扫一扫\n商品条形码',
                          textAlign: TextAlign.center,
                          style: XStyleUtils.getTextStyle(
                            fontSize: 26,
                            color: RBColors.reabamColor4,
                          ),
                        ),
                      ])),
                ),
                XWidgetUtils.getLayoutExpanded(XWidgetUtils.getLayoutContainer(
                  alignment: Alignment.topCenter,
                  margin: XWidgetUtils.getEdgeInsets(0, 45, 0, 0),
                  child: XImageUtils.getImageWidgetWithAsset(
                    'ss_arr_right.png',
                    width: 40,
                    height: 40,
                  ),
                )),
                XWidgetUtils.getLayoutContainer(
                    child: XWidgetUtils.getLayoutColumn(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        shrinkWrap: true,
                        children: [
                      XImageUtils.getImageWidgetWithAsset(
                        'ss_homeindex_3.png',
                        width: 120,
                        height: 120,
                      ),
                      XWidgetUtils.getWidgetText(
                        '完成支付\n（等待打印小票）',
                        textAlign: TextAlign.center,
                        style: XStyleUtils.getTextStyle(
                          fontSize: 26,
                          color: RBColors.reabamColor4,
                        ),
                      ),
                    ])),
              ])),
      XWidgetUtils.getLayoutContainer(
          margin: XWidgetUtils.getEdgeInsets(0, 166, 0, 0),
          alignment: Alignment.center,
          child: XImageUtils.getImageWidgetWithAsset(
            'ss_homeindex_big_logo.png',
            width: 531,
            height: 531,
          )),
      XWidgetUtils.getWidgetGestureDetector(
          child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
              margin: XWidgetUtils.getEdgeInsets(91, 137, 91, 0),
              radius_bottomLeft: 16,
              radius_bottomRight: 16,
              radius_topRight: 16,
              radius_topLeft: 16,
              height: 120,
              alignment: Alignment.center,
              backgroundColor: RBColors.reabamColor4,
              child: XWidgetUtils.getWidgetText(
                '会员结算',
                textAlign: TextAlign.center,
                style: XStyleUtils.getTextStyle(
                  fontSize: 46,
                  color: Colors.white,
                ),
              )),
          onTap: () {
            startPage(PageStateSelfServiceSelectMember());
          }),
      XWidgetUtils.getWidgetGestureDetector(
          child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
              margin: XWidgetUtils.getEdgeInsets(91, 42, 91, 0),
              radius_bottomLeft: 16,
              radius_bottomRight: 16,
              radius_topRight: 16,
              radius_topLeft: 16,
              height: 120,
              alignment: Alignment.center,
              backgroundColor: Colors.white,
              borderColor: RBColors.reabamColor4,
              borderWidth: 3,
              child: XWidgetUtils.getWidgetText(
                '非会员结算',
                textAlign: TextAlign.center,
                style: XStyleUtils.getTextStyle(
                  fontSize: 46,
                  color: RBColors.reabamColor4,
                ),
              )),
          onTap: () {
            startPage(PageStateSelfServiceShoppingCart(member: null));
          })
    ]));
  }

  @override
  void onStart() {}

  @override
  Future<void> updateData({int pageIndex = 1}) async {}

  _initSomeData() {
    //init
    XSharePreferencesUtils.saveString(RBConfigs.SP_kuaimai_templateId, '');
    XSharePreferencesUtils.saveString(RBConfigs.SP_docTypeInfo, '');

    RBBaseApi.getShopCartDetail(succeed: (response,
        Map<String, dynamic> responseMap,
        Map<String, dynamic> headers_response) {
      dynamic data = responseMap['data'];
      /*
            导购
            {
			"rate":null,
			"staffCode":"",
			"staffId":"3c38f8543a714fab84ff6d6521afeacc",
			"staffName":"杨定雯"
		}
             */
      dynamic staff = data?['staff'];
      XLogUtils.printLog('---getShopCartDetail,staff=$staff');
      XSharePreferencesUtils.saveString(
          RBConfigs.SP_staff, XJsonUtils.obj2Json(staff));

      //
      dynamic docTypeInfo = data?['docTypeInfo'];
      dynamic docType = docTypeInfo?['docType']; //Retail
      dynamic docTypeName = docTypeInfo?['docTypeName']; //零售
      dynamic orderTypeCode = docTypeInfo?['orderTypeCode']; //CX0007843
      dynamic orderTypeName = docTypeInfo?['orderTypeName']; //零售订单

      XLogUtils.printLog('---getShopCartDetail,docTypeInfo=$docTypeInfo');
      XSharePreferencesUtils.saveString(
          RBConfigs.SP_docTypeInfo, XJsonUtils.obj2Json(docTypeInfo));

      //获得打印设置
      RBBaseApi.getPrintSet(succeed: (response,
          Map<String, dynamic> responseMap,
          Map<String, dynamic> headers_response) {
        /*
          {
           "docType":"CX0008007",
            "docTypeName":"零售",
           "id":"42811",
           "onlineTemplateId":"1634959500",
            "optionName":"SalesOrder",
           "source":"PrinterTicketCustom",
            "templateFileUrl":"",
            "templateId":"73653"
          }
           */
        List<dynamic> printerTicketCustom =
            responseMap['printerTicketCustom'] ?? [];
        String onlineTemplateId = '';
        for (dynamic iitem in printerTicketCustom) {
          if (iitem['docType'] == orderTypeCode) {
            onlineTemplateId = iitem['onlineTemplateId'];
            XSharePreferencesUtils.saveString(
                RBConfigs.SP_kuaimai_templateId, onlineTemplateId);
            break;
          }
        }

        XLogUtils.printLog('---getPrintSet,onlineTemplateId=$onlineTemplateId');
      }, failed: (String code, String msg) {
        //
      });
    }, failed: (String code, String msg) {
      //
    });

    RBBaseApi.getSelfServiceSettingInfo(succeed: (response,
        Map<String, dynamic> responseMap,
        Map<String, dynamic> headers_response) {
      dynamic selfCheckoutSet = responseMap['data']?['selfCheckoutSet'];
      //
      XSharePreferencesUtils.saveBool(RBConfigs.SP_cartEnableOptionalItems,
          selfCheckoutSet?['cartEnableOptionalItems'] ?? false);
      //
      Map<String, dynamic> cartRelatedItem = {};
      cartRelatedItem['cartRelatedItemId'] =
          selfCheckoutSet?['cartRelatedItemId'];
      cartRelatedItem['cartRelatedItemName'] =
          selfCheckoutSet?['cartRelatedItemName'];
      cartRelatedItem['cartRelatedItemAlias'] =
          selfCheckoutSet?['cartRelatedItemAlias'];
      XSharePreferencesUtils.saveString(
          RBConfigs.SP_cartRelatedItem, XJsonUtils.obj2Json(cartRelatedItem));
      //
      XSharePreferencesUtils.saveBool(RBConfigs.SP_orderDefaultTypeEnabled,
          selfCheckoutSet?['orderDefaultTypeEnabled'] ?? false);
      Map<String, dynamic> orderDefaultType = {};
      orderDefaultType['orderTypeCode'] = selfCheckoutSet?['orderTypeCode'];
      orderDefaultType['orderTypeName'] = selfCheckoutSet?['orderTypeName'];
      XSharePreferencesUtils.saveString(
          RBConfigs.SP_orderDefaultType, XJsonUtils.obj2Json(orderDefaultType));
    }, failed: (String code, String msg) {
      //
    });
  }

  @override
  Color getXPageBackgroundColor() {
    return Colors.white;
  }

  //监控扫描///////////////////////////////////////////////
  @override
  bool getIsReceiveProjectNativeMessage() {
    return true;
  }

  @override
  void onReceiveProjectNativeMessageCallback(resultMap) {
    String type = resultMap['type'] ?? '';
    if (type == 'android_keyboard_listener') {
      String outputStr = resultMap['data'] ?? '';
      XLogUtils.printLog(
          '---android_keyboard_listener,isPageScanType=${RBConfigs.isPageScanType}, outputStr=$outputStr');
      if (XStringUtils.isEmpty(outputStr)) {
        return;
      }

      if (RBConfigs.isPageScanType == 1) {
        //扫描搜索商品添加购物车
        RBBusinessUtils.scanFindGood_and_addToShoppingcart_selfService(
            this, outputStr);
      } else if (RBConfigs.isPageScanType == 2) {
        //扫描支付
        RBBusinessUtils.pay_selfService(this, outputStr);
      }
    }
  }
}
